package com.teaching.management.controller.api;

import com.teaching.management.entity.CourseSelection;
import com.teaching.management.entity.User;
import com.teaching.management.repository.CourseSelectionRepository;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 成绩管理相关的REST API
 */
@RestController
@RequestMapping("/api/admin/grades")
public class AdminGradeRestController {

    @Autowired
    private CourseSelectionRepository courseSelectionRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 获取所有成绩记录
     */
    @GetMapping
    public ResponseEntity<?> getAllGrades(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        List<CourseSelection> gradesRecords = courseSelectionRepository.findAll();
        return ResponseEntity.ok(gradesRecords);
    }

    /**
     * 根据条件搜索成绩
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchGrades(
            @RequestParam(value = "studentId", required = false) String studentId,
            @RequestParam(value = "courseId", required = false) String courseId,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 创建查询条件
        CourseSelection example = new CourseSelection();
        if (studentId != null && !studentId.isEmpty()) {
            example.setStudentId(studentId);
        }
        if (courseId != null && !courseId.isEmpty()) {
            example.setCourseId(courseId);
        }

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        List<CourseSelection> gradesRecords = courseSelectionRepository.findAll(Example.of(example, matcher));
        return ResponseEntity.ok(gradesRecords);
    }

    /**
     * 获取单个成绩记录详情
     */
    @GetMapping("/{selectionId}")
    public ResponseEntity<?> getGrade(@PathVariable Integer selectionId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        Optional<CourseSelection> gradeOpt = courseSelectionRepository.findById(selectionId);
        if (gradeOpt.isPresent()) {
            return ResponseEntity.ok(gradeOpt.get());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("成绩记录不存在");
        }
    }

    /**
     * 更新成绩
     */
    @PutMapping("/{selectionId}")
    public ResponseEntity<?> updateGrade(
            @PathVariable Integer selectionId,
            @RequestBody Map<String, Object> gradeData,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查选课记录是否存在
        Optional<CourseSelection> courseSelectionOpt = courseSelectionRepository.findById(selectionId);
        if (!courseSelectionOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("成绩记录不存在");
        }

        // 获取要更新的成绩
        Number gradeValue = (Number) gradeData.get("grade");
        if (gradeValue == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("成绩不能为空");
        }

        // 更新成绩
        CourseSelection courseSelection = courseSelectionOpt.get();
        courseSelection.setScore(new BigDecimal(gradeValue.toString()));

        CourseSelection updatedSelection = courseSelectionRepository.save(courseSelection);
        return ResponseEntity.ok(updatedSelection);
    }

    /**
     * 批量更新成绩
     */
    @PutMapping("/batch")
    public ResponseEntity<?> updateGradesBatch(
            @RequestBody List<Map<String, Object>> gradesData,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        for (Map<String, Object> gradeData : gradesData) {
            Integer selectionId = (Integer) gradeData.get("selectionId");
            Number gradeValue = (Number) gradeData.get("grade");

            if (selectionId == null || gradeValue == null) {
                continue; // 跳过无效数据
            }

            // 检查选课记录是否存在
            Optional<CourseSelection> courseSelectionOpt = courseSelectionRepository.findById(selectionId);
            if (!courseSelectionOpt.isPresent()) {
                continue; // 跳过不存在的记录
            }

            // 更新成绩
            CourseSelection courseSelection = courseSelectionOpt.get();
            courseSelection.setScore(new BigDecimal(gradeValue.toString()));
            courseSelectionRepository.save(courseSelection);
        }

        return ResponseEntity.ok().body("批量更新成绩成功");
    }
}